<?php


namespace App\Http\Controllers\Api;


use App\Models\WxShopOrder;
use App\Models\WxUserFinancial as Model;
use App\Models\WxExceptional;
use App\Models\WxNotice;
use App\Models\WxOrder;
use App\Models\WxUser;
use App\Models\WxUserFinancial;

class NotifyController
{
    public function index()
    {
        $xml = file_get_contents('php://input');
        libxml_disable_entity_loader(true);
        $xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
        $valArr = json_decode(json_encode($xmlstring), true);

        $out_trade_no = $valArr['out_trade_no'];//支付回调订单号
        $transaction_id = $valArr['transaction_id'];//支付回调支付号
        $time_end = $valArr['time_end'];//支付回调支付时间
        $payment_time = date('Y-m-d H:i:s', strtotime($time_end));
        $total_fee = $valArr['total_fee'];//支付回调支付金额
        $payed = $total_fee / 100;

        if (empty($out_trade_no)) {
            die('错误');
        }


        $isExists = WxOrder::where('order_number', $out_trade_no)->exists();
        if ($isExists) {
            WxOrder::where('order_number', $out_trade_no)->update(['order_state' => 1, 'order_serial_number' => $transaction_id]);
            $type = WxOrder::where('order_number', $out_trade_no)->value('order_type');
            // 开会员
            if ($type == 1) {
                $uid = WxOrder::where('order_number', $out_trade_no)->value('user_id');
                $this->vip($uid);
            }
            // 打赏
            if ($type == 2) {
                $order = WxOrder::where('order_number', $out_trade_no)->first(['user_id', 'order_pay_price', 'parame']);
                $this->exceptional($order);
            }
        } else {
            //SHOP
            WxShopOrder::where('order_id', $out_trade_no)
                ->update(['pay_status' => 2, 'status' => 1, 'serial_number' => $transaction_id, 'payment_time' => $payment_time, 'payed' => $payed]);
        }

        return $this->successXml();
    }

    /**
     * 开通会员
     * @param $uid
     */
    private function vip($uid)
    {
        WxUser::where('id', $uid)->update(['is_member' => 1]);
        (new WxNotice())->addNotice($uid, '开通会员', '您已成功开通会员服务', 0);
    }

    /**
     * 打赏
     * @param $order
     */
    private function exceptional($order)
    {
        $data = unserialize($order['parame']);

        (new WxExceptional())->addExceptional($order['user_id'], $data['postsId'], $data['postsUserId'], $order['order_pay_price']);

        $financial = WxUserFinancial::where('user_id', $data['postsUserId'])->exists();
        if ($financial) {
            $uf = WxUserFinancial::where('user_id', $data['postsUserId'])->first();
            $balance = $uf['balance'] + $order['order_pay_price'];
            $sumPrice = $uf['sum_price'] + $order['order_pay_price'];
            WxUserFinancial::where('user_id', $data['postsUserId'])
                ->update(['balance' => $balance, 'sum_price' => $sumPrice,]);
        } else {
            $userFinancialModel = new Model();
            $userFinancialModel->user_id = $data['postsUserId'];
            $userFinancialModel->balance = $order['order_pay_price'];
            $userFinancialModel->sum_price = $order['order_pay_price'];
            $userFinancialModel->save();
        }

        $user_name = WxUser::where('id', $order['user_id'])->value('user_name');
        (new WxNotice())->addNotice($data['postsUserId'], '收到打赏', '您收到了一笔来着「' . $user_name . '」的打赏，打赏金额¥' . $order['order_pay_price'], 6, $data['postsId']);
    }


    private function successXml()
    {
        $arr = ['return_code' => 'SUCCESS', 'return_msg' => 'OK'];
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_array($val)) {
                $xml .= "<" . $key . ">" . arrayToXml($val) . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            }
        }
        $xml .= "</xml>";
        return $xml;
    }

}
